package controller;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.Enterprise;
import model.UserAccount;
import util.Log;
import validator.EnterpriseValidator;
import web.JSONMessage;
import db.ImbiConnection;
import facade.EnterpriseFacade;

public class EnterpriseManageController extends HttpServlet{

	private static final long serialVersionUID = 1L;
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		UserAccount u = (UserAccount)request.getSession().getAttribute("user");
		if(u != null){
			if(request.getParameter("delete")!= null){
				deleteEnterprise(request, response, u);
			} else addEnterprise(request, response, u);
		}		
	}
	private void deleteEnterprise(HttpServletRequest request,
			HttpServletResponse response, UserAccount u) throws IOException {		
		try{
			int id = Integer.parseInt(request.getParameter("id"));		
			Enterprise e = ImbiConnection.getEnterpriseDAO().find(id);
			if(e != null){
				EnterpriseFacade.deleteEnterprise(e);
				response.getWriter().write(JSONMessage.message("Enterprise and related data deleted!"));				
				Log.write(u.getUsername()+" deleted enterprise "+e.getFullName());
			} else throw new NumberFormatException();
		} catch(NumberFormatException e){
			response.getWriter().write(JSONMessage.errorMessage("Invalid parameters"));
		}
	}
	private void addEnterprise(HttpServletRequest request,
			HttpServletResponse response, UserAccount u)
			throws ServletException, IOException {
		EnterpriseValidator validator = new EnterpriseValidator(
			"0", 
			request.getParameter("name"),
			request.getParameter("fullname")
		);
		
		if(validator.isValid()){
			ImbiConnection.getEnterpriseDAO().insert(
				new Enterprise(
					0, 
					validator.getName(), 
					validator.getFullname(), 
					u.getEmployee().getId(), 
					u.getEmployee().getId(), 
					new Date(), 
					new Date()
				)				
			);
			Log.write(u.getUsername()+" added enterprise "+validator.getFullname());
		}
			
		
		request.setAttribute("enterprise", ImbiConnection.getEnterpriseDAO().findAll());
		request.getRequestDispatcher("/WEB-INF/enterprise.jsp").forward(request, response);
	}
	
}
